home *** CD-ROM | disk | FTP | other *** search
- Path: castle.nando.net!news
- From: actuary@nando.net (Bill McCarthy)
- Newsgroups: comp.lang.c
- Subject: Re: quick decision: is n a power of 2?
- Date: 21 Jan 1996 01:02:49 GMT
- Organization: News & Observer Public Access
- Message-ID: <4ds3bp$k5m@castle.nando.net>
- References: <Pine.OSF.3.91.960119114608.18779E-100000@io.UWinnipeg.ca> <4dp8cr$sit@crl.crl.com>
- Reply-To: actuary@nando.net (Bill McCarthy)
- NNTP-Posting-Host: grail1007.nando.net
- X-Newsreader: IBM NewsReader/2 v1.2
-
- In <4dp8cr$sit@crl.crl.com>, bobfry@crl.com (Robert Fry) writes:
- >Someone was asking for a quick way to determine if a number is a power of
- >2. The solutions I've seen involved ounting every bit and seeing if the
- >number of 'on' bits is 1. But why not take advantage of the binary
- >representation of numbers and use:
- >
- >int is_power_of_2( long num)
- >{
- > return((( num - 1) & num) == 0);
- >}
-
- You don't really want signed do you? And is zero a power
- of 2? (maybe pow(2,-inf)?) How about:
-
- int is_power_of_2( unsigned long n )
- {
- return !(n - 1 & n) && n != 0;
- }
-
- Bill McCarthy
- actuary@nando.net
- Wendell, NC USA
-